<template>
    <!-- 登录页面容器 -->
    <div class="login-page">
        <!-- 登录表单盒子 -->
        <div class="login-box">
            <!-- 登录方式标题 -->
            <div class="login-title">
                <span :class="{ active: loginType === 'quick' }" @click="switchLoginType('quick')">快速登录</span>
                <span>|</span>
                <span :class="{ active: loginType === 'account' }" @click="switchLoginType('account')">账号登录</span>
            </div>

            <!-- 快速登录（手机验证码）表单 -->
            <div v-if="loginType === 'quick'" class="form-group">
                <div class="form-field">
                    <div class="input-label">手机号码</div>
                    <input v-model="phone" placeholder="请输入手机号码" class="input-field" />
                </div>
                <div class="form-field">
                    <div class="input-label">验证码</div>
                    <div class="code-input-container">
                        <input v-model="code" placeholder="请输入验证码" class="input-field code-input" />
                        <button class="get-code-btn" @click="sendCode" :disabled="isSendingCode">
                            {{ codeButtonText }}
                        </button>
                    </div>
                </div>
            </div>

            <!-- 账号登录表单 -->
            <div v-else class="form-group">
                <div class="form-field">
                    <div class="input-label">账号</div>
                    <input v-model="account" placeholder="请输入用户名/手机号" class="input-field" />
                </div>
                <div class="form-field">
                    <div class="input-label">密码</div>
                    <input v-model="password" type="password" placeholder="请输入密码" class="input-field" />
                </div>
            </div>

            <!-- 登录按钮 -->
            <button class="login-btn" @click="handleLogin">
                登录
            </button>

            <!-- 协议勾选 -->
            <div class="protocol-agreement">
                <input type="checkbox" v-model="agreeProtocol" id="agreeProtocol" class="protocol-checkbox" />
                <label for="agreeProtocol">已阅读并同意《用户协议》和《隐私协议》</label>
            </div>
            <!-- <van-dialog v-model:show="loading" title="微信登录" :show-confirm-button="false">
                <img :src="qr_url" alt="微信登录二维码" />
            </van-dialog> -->
        </div>
    </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import api from '@/api/history'
import axios from 'axios'
// import { get } from '../request/http'
// import { showToast } from 'vant'

const router = useRouter()
const loginType = ref('account')
const phone = ref('')
const code = ref('')
const account = ref('')
const password = ref('')
const agreeProtocol = ref(false)
const isSendingCode = ref(false)
// const loading = ref(false)

// const appId = import.meta.env.VITE_WECHAT_APP_ID || 'wx288d3bd0b6a31aec' // 请替换为您的微信AppID
// const redirectUri = encodeURIComponent("http://weigediao.com/wechat-callback")
let qr_url = ref('')

let countDown = 0
let codeTimer = null



const codeButtonText = computed(() => {
    return isSendingCode.value ? `${countDown}s后重新获取` : '获取验证码'
})

const handleBack = () => {
    router.go(-1)
}

const switchLoginType = (type) => {
    loginType.value = type
    resetForm()
}

const resetForm = () => {
    phone.value = ''
    code.value = ''
    account.value = ''
    password.value = ''
    isSendingCode.value = false
    codeTimer && clearInterval(codeTimer)
}

const sendCode = () => {
    if (!phone.value) {
        alert('请输入手机号码')
        return
    }

    isSendingCode.value = true
    countDown = 60

    api.post(`/user/api/send_sms_code`, { phone: phone.value })
        .then((res) => {
            if (res.data.success) {
                startCodeTimer()
            } else {
                handleApiError(res.data.message || '验证码发送失败')
            }
        })
        .catch((err) => {
            // 更详细的错误处理
            if (err.response && err.response.status === 422) {
                handleApiError('数据格式错误，请检查输入')
            } else {
                handleApiError('网络异常，请稍后再试')
            }
            console.error('错误详情:', err)
        })
}

const startCodeTimer = () => {
    codeTimer = setInterval(() => {
        countDown--
        if (countDown <= 0) {
            clearInterval(codeTimer)
            isSendingCode.value = false
        }
    }, 1000)
}

const handleLogin = () => {
    if (!validateForm()) return

    const apiUrl = loginType.value === 'quick'
        ? '/user/login/quick'
        : '/user/login/account'
    const requestData = loginType.value === 'quick'
        ? { phone: phone.value, code: code.value }
        : { username: account.value, password: password.value }

    if (loginType.value === 'quick') {
        const phoneRegex = /^1[3-9]\d{9}$/
        if (!phoneRegex.test(phone.value)) {
            alert('请输入有效的11位手机号码')
            return
        }
    }

    // 修改为使用 api 实例发送请求
    api.post(apiUrl, requestData)
        .then((res) => {
            // 账号登录接口成功返回token即表示登录成功
            console.log('登录成功返回信息', res.data);
            if (res.data.access_token) {
                // 保存token到本地存储
                localStorage.setItem('token', res.data.access_token)
                handleLoginSuccess();
            } else {
                handleApiError(res.data.detail || '登录失败');
            }
        })
        .catch((err) => {
            // 更详细的错误处理
            if (err.response?.status === 422) {
                handleApiError("数据格式错误：请检查手机号和验证码");
            } else {
                handleApiError("网络异常，请稍后再试");
            }
        });
};

const validateForm = () => {
    if (!agreeProtocol.value) {
        alert('请先同意用户协议和隐私协议')
        return false
    }

    if (loginType.value === 'quick') {
        if (!phone.value || !code.value) {
            alert('请填写手机号和验证码')
            return false
        }
    } else {
        if (!account.value || !password.value) {
            alert('请填写账号和密码')
            return false
        }
    }
    return true
}

const handleLoginSuccess = () => {
    const redirect = router.currentRoute.value.query.redirect || '/home'
    router.push(redirect)
}

const handleApiError = (message) => {
    alert(message)
    isSendingCode.value = false
}
</script>

<style scoped>
/* 页面整体布局 */
.login-page {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    min-height: 100vh;
    background-color: #f5f5f5;
    padding: 20px;
    font-family: Arial, sans-serif;
}

/* 登录盒子容器 */
.login-box {
    width: 100%;
    max-width: 400px;
    background-color: #fff;
    border-radius: 8px;
    padding: 30px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

/* 登录标题 */
.login-title {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 30px;
    font-size: 18px;
    color: #333;
}

.login-title span {
    margin: 0 10px;
    cursor: pointer;
}

.login-title span.active {
    font-weight: bold;
}

.login-title span:nth-child(2) {
    color: #ccc;
    cursor: default;
}

/* 表单组 */
.form-group {
    margin-bottom: 25px;
}

.form-field {
    margin-bottom: 20px;
}

.input-label {
    margin-bottom: 8px;
    font-size: 14px;
    color: #333;
}

.input-field {
    width: 100%;
    padding: 12px;
    border: 1px solid #ddd;
    border-radius: 4px;
    font-size: 14px;
    box-sizing: border-box;
}

.code-input-container {
    display: flex;
    align-items: center;
}

.code-input {
    flex: 1;
    margin-right: 10px;
}

.get-code-btn {
    padding: 12px 15px;
    background-color: #f0f0f0;
    border: 1px solid #ddd;
    border-radius: 4px;
    font-size: 14px;
    color: #333;
    cursor: pointer;
    white-space: nowrap;
}

.get-code-btn:disabled {
    color: #999;
    cursor: not-allowed;
}

/* 登录按钮 */
.login-btn {
    width: 100%;
    padding: 12px;
    color: white;
    border: none;
    border-radius: 4px;
    font-size: 16px;
    cursor: pointer;
    margin-bottom: 20px;
}


/* 协议勾选 */
.protocol-agreement {
    display: flex;
    align-items: center;
    font-size: 14px;
    color: #666;
}

.protocol-checkbox {
    margin-right: 8px;
}
</style>